/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pa165.dominatingspecies.frontend.animal;

import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.springframework.dao.DataAccessException;
import org.springframework.security.access.prepost.PreAuthorize;
import pa165.dominating.species.tos.AnimalTo;
import pa165.dominating.species.tos.EnvironmentTo;
import pa165.dominatingspecies.service.impl.AnimalServiceImpl;

/**
 *
 * @author Filip
 */
@PreAuthorize("hasRole('WORKER')")
public class RemoveAnimalLink extends Link<Void> {

    @SpringBean(name = "animalService")
    private AnimalServiceImpl animalService;
    private final AnimalTo source;
    private final AnimalTo target;
    private EnvironmentTo filter;
    private boolean manipulatingPrey;

    public RemoveAnimalLink(String componentId, AnimalTo source, AnimalTo target, EnvironmentTo filter, boolean manipulatingPrey) {
        super(componentId);
        this.source = source;
        this.target = target;
        this.filter = filter;
        this.manipulatingPrey = manipulatingPrey;

    }

    @Override
    public void onClick() {
        boolean thrown = false;
        try {
            if (manipulatingPrey) {
                animalService.removePreyOfPredator(source, target);
            } else {
                animalService.removePreyOfPredator(target, source);
            }


        } catch (DataAccessException ex) {
            thrown = true;
            if (manipulatingPrey) {
                getSession().warn(new StringResourceModel("preyRemoveFailed", this, null, new Object[]{target.getId()}).getString());
            } else {
                getSession().warn(new StringResourceModel("predatorRemoveFailed", this, null, new Object[]{target.getId()}).getString());
            }

            System.out.println(ex.getMessage());
            setResponsePage(new AnimalPreyPredatorsPage(source.getId(), filter, manipulatingPrey));
        }
        if (!thrown) {
            if (manipulatingPrey) {
                getSession().info(new StringResourceModel("preyRemoveSucc", this, null, new Object[]{target.getId()}).getString());
            } else {
                getSession().info(new StringResourceModel("predatorRemoveSucc", this, null, new Object[]{target.getId()}).getString());
            }

            setResponsePage(new AnimalPreyPredatorsPage(source.getId(), filter, manipulatingPrey));
        }
    }
}
